import json as jsonloads

from sanic import Sanic, response
from sanic.exceptions import NotFound
from sanic.response import json, html, redirect
from sanic_openapi import swagger_blueprint

from apps.views import index_bp
from news import get_news
from saniclocal import SanicLocal

app = Sanic(__name__)
app.blueprint(swagger_blueprint)
app.blueprint(index_bp)

app.static("/static", "./static")



@app.route("/")
async def test(request):
    return json({"hello": "world"})


@app.route('/favicon.ico')
async def favicon(request):
    return response.redirect(app.url_for('static', filename=SanicLocal.faviconpath))


@app.route("/news/<page:int>")
@app.route("/news")
async def index(request, page=1):
    """

    :param request:
    :param page:  Description
    :return:
    """
    # html页面模板
    html_tem = """
    <div style="width: 80%; margin-left: 10%">
        <p><a href="{href}" target="_blank">{title}</a></p>
        <p>{summary}</p>
         <p>{updated_at}</p>
    </div>
    """
    html_list = []
    # 获取数据
    all_news = await get_news(page * 10)
    # 生成在浏览器展示的html页面
    for each_news in all_news:
        html_list.append(html_tem.format(
            href=each_news.get('news_info', [{}])[0].get('url', '#'),
            title=each_news.get('title'),
            summary=each_news.get('summary'),
            updated_at=each_news.get('updated_at'),
        ))

    return html('<hr>'.join(html_list))


@app.route("/json", methods=["GET", "POST"])
async def json_reuqets(request):
    html_tem = """
     <form action="/json" method="post" enctype="multipart/form-data">
        <textarea name="mytextarea" rows="30" cols="200"></textarea>
        <br>
        <input type="submit" name="submit" class="btn" value="上传" />
    </form>
    """
    if request.method == "POST":
        jsons = request.form.get("mytextarea")
        jsons = jsonloads.loads(jsons)
        return json(jsons)
    else:
        return html(html_tem)


@app.exception(NotFound)
def ignore_404s(request, exception):
    return redirect('/')


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000, debug=True)
